<template>
  <div>
    <div class="login-container">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">

        <div class="title-container">
          <h3 class="title">Login Form</h3>
        </div>

        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="Username"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
        </el-form-item>

        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="Password"
              name="password"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-tooltip>
        <div>
          <!--          id="TencentCaptcha"-->
          <!--          data-appid="2061024774"-->
          <!--          data-cbfn="verifyCallback"-->
          <!--          type="button"-->
          <!--          class="el-button"-->
          <el-button
            v-if="isNotVerified"
            :loading="loading"
            style="width:100%;margin-bottom:30px;    background: #66b1ff;    border-color: #66b1ff;    color: #FFF;"
            @click="verify"
          >验证</el-button>
          <div v-else>
            <el-button :disabled="isNotVerified" :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登录</el-button>
            <el-button style="width:100%;margin-bottom:30px;margin-left: -2px" type="primary" @click="isRegisterVisible=true">
              注册
            </el-button>
          </div>
        </div>
        <el-button type="success" style="width:100%;margin-bottom:30px;margin-left: -2px" @click="sendMessage">扫码登录</el-button>

      </el-form>
    </div>
    <el-dialog title="账号注册" :visible.sync="isRegisterVisible">
      <el-row style="margin-top: 5px">
        <el-col :span="11">
          <div>
            <h2>小程序注册</h2>
            <img width="400" height="400" src="../../assets/login/goto.jpg" alt="?">
          </div>
        </el-col>
        <el-col :span="1"> <el-divider direction="vertical" /></el-col>

        <el-col :span="12">
          <h2>系统注册</h2>
          <div style="margin-top: 30px">
            <el-input v-model="user.username" class="registerInput" style="outline:none" placeholder="请输入账号名" minlength="8" maxlength="15" show-word-limit />
            <el-input v-model="user.password" class="registerInput" style="outline:none" placeholder="请输入密码" minlength="8" show-password show-word-limit />
            <el-input v-model="confirmPassword" class="registerInput" style="outline:none" placeholder="确认没密码" minlength="8" show-password show-word-limit />
            <p v-if="isTipShow" style="font-size: 12px ; "> 密码不一致 </p>
            <el-input v-model="user.area" class="registerInput" style="outline:none" placeholder="住址" minlength="8" maxlength="20" show-word-limit />
            <el-input v-model="user.realName" class="registerInput" placeholder="姓名" minlength="2" maxlength="10" show-word-limit />
            <el-input v-if="isRegisterWorker" v-model="code" class="registerInput" placeholder="邀请码" show-word-limit />
            <el-switch
              v-model="isRegisterWorker"
              style="display: block"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="注册为工作者"
              inactive-text="注册为用户"
            />
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="registerAccount">注册</el-button>
      </div>

    </el-dialog>
    <el-dialog title="小程序登录" :visible.sync="isCodeShow">
      <div style="margin: auto">
        <img :src="codeUrl" alt="?">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import request from '@/utils/request'
const QRCode = require('qrcode')
import { v1 as uuidv1 } from 'uuid'
import { getToken } from '../../utils/auth'
import { Message } from 'element-ui'
let vm = null
// window.verifyCallback = function(res) {
//   console.log(res)
//   // res（用户主动关闭验证码）= {ret: 2, ticket: null}
//   // res（验证成功） = {ret: 0, ticket: "String", randstr: "String"}
//   if (res.ret === 0) {
//     const data = { 'ticket': res.ticket, 'randInt': res.randstr }
//     request({
//       url: 'https://www.laozhoy1.club/authentication/verify',
//       // url: 'https://localhost/authentication/verify',
//       method: 'get',
//       params: data
//     }).then(function(res) {
//       if (res.code === 20000) {
//         vm.isNotVerified = false
//       }
//     })
//   }
// }
export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      canRegister: false,
      isTipShow: false,
      loginForm: {
        username: 'testName',
        password: 'testPassword'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      user: {
        username: '',
        password: '',
        realName: '',
        area: ''
      },
      passwordType: 'password',
      code: '',
      isRegisterWorker: false,
      confirmPassword: '',
      capsTooltip: false,
      isNotVerified: true,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      isRegisterVisible: false,
      socket: null,
      isCodeShow: false,
      uuid: null,
      codeUrl: null
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    },
    confirmPassword: function(oldValue, newValue) {
      if (this.confirmPassword !== this.user.password) {
        this.isTipShow = true
      } else {
        this.isTipShow = false
      }
    }
  },
  created() {
    vm = this
    const v1options = {
      node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
      clockseq: 0x1234,
      msecs: new Date().getTime(),
      nsecs: 5678
    }
    this.uuid = uuidv1(v1options)
    // eslint-disable-next-line handle-callback-err
    QRCode.toDataURL(this.uuid, function(err, url) {
      vm.codeUrl = url
    })
    this.isNotVerified = true
    // this.socket = new WebSocket('wss://localhost/qrcodeWebsocket/' + this.uuid)
    this.socket = new WebSocket('wss://www.laozhoy1.club/qrcodeWebsocket/' + this.uuid)
    this.socket.onerror = err => {
      console.log(err)
    }
    this.socket.onopen = event => {
      console.log(event)
    }
    this.socket.onmessage = mess => {
      console.log(mess.data)
      this.$store.dispatch('user/loginByCode', mess.data.replace(/"/g, ''))
        .then(function() {
          const hasToken = getToken()
          console.log('接受信息  token为：' + hasToken)
          vm.$router.push({ path: '/' })
        })
    }
    this.socket.onclose = () => {
      console.log('连接关闭')
    }
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
    this.isNotVerified = true
  },
  destroyed() {
  },
  methods: {
    registerAccount() {
      const vm = this
      if (this.user.username.length > 0 && this.user.username.length < 15) {
        if (this.user.password.length >= 8 && this.user.password.length < 15) {
          if (this.user.password === this.confirmPassword) {
            if (this.user.area.length > 0 && this.user.area.length <= 20) {
              if (this.user.realName.length > 1 && this.user.realName.length <= 10) {
                if (this.isCodeShow === true && this.code.length === 5) {
                  // url: 'https://localhost/authentication/register',
                  request({
                    url: 'https://www.laozhoy1.club/authentication/register',
                    method: 'post',
                    params: { 'invitecode': vm.code },
                    body: vm.user
                  }).then(function() {
                    Message.success('注册成功')
                    vm.isRegisterVisible = true
                  })
                } else if (this.isCodeShow === false) {
                  request({
                    url: 'https://www.laozhoy1.club/authentication/register',
                    method: 'post',
                    data: vm.user
                  }).then(function() {
                    Message.success('注册成功')
                    vm.isRegisterVisible = true
                  })
                } else {
                  Message.info('邀请码不规范')
                }
              } else {
                Message.info('真实姓名不能为空')
              }
            } else {
              Message.info('住址不能为空')
            }
          } else {
            Message.info('两次密码不一致')
          }
        } else {
          Message.info('密码不规范，长度控制在1~15之间')
        }
      } else {
        Message.info('用户名称呼不规范，长度控制在1~15之间')
      }
    },
    verify() {
      const vm = this
      vm.loading = true
      setTimeout(function() {
        vm.isNotVerified = false
        vm.loading = false
      }, 2000)
    },
    sendMessage() {
      this.isCodeShow = true
      if (this.socket.readyState === 1) {
        this.socket.send(this.uuid)
      } else alert('尚未建立websocket连接')
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg:#283443;
  $light_gray:#fff;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }
  .el-divider--vertical{
    height: 34em;
  }
  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg:#2d3a4b;
  $dark_gray:#889aa4;
  $light_gray:#eee;
  .registerInput{
    margin: 10px;
  }
  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;
    background-image: url('../../assets/login/loginbakc.jpg');
    height: 975px;
    .login-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 160px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .thirdparty-button {
      position: absolute;
      right: 0;
      bottom: 6px;
    }

    @media only screen and (max-width: 470px) {
      .thirdparty-button {
        display: none;
      }
    }
  }
</style>
